<template>
  <div class="app-container">
    <div class="flex">
      <div class="custom-tag">
        <el-radio-group v-model="radioCon" size="large">
          <el-radio-button :label="item.value" :value="item.value" v-for="(item,index) in coo_meeting_type" :key="index"
            @click="bindRadio(item.label,item.value)">{{item.label}}</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="收费站" prop="deptId" v-if="deptId==101">
        <el-tree-select style="width: 100%;" v-model="queryParams.deptId" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }"
          value-key="id" placeholder="请选择" check-strictly />

      </el-form-item>
      <el-form-item label="会议时间" style="width: 308px">
        <el-date-picker v-model="dateSection" value-format="YYYY-MM-DD" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
          @change="bindChangeAllDate"></el-date-picker>
      </el-form-item>
      <el-form-item label="会议名" prop="meetingName">
        <el-input v-model="queryParams.meetingName" placeholder="请输入会议名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['coordination:meeting:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['coordination:meeting:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Menu" @click="handleStatistics">统计</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="meetingList" @selection-change="handleSelectionChange" show-overflow-tooltip>

      <el-table-column label="序号" type="index" width="65" align="center" />
      <el-table-column label="收费站" align="center" prop="deptName" />
      <el-table-column label="会议时间" align="center" prop="seminarDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.seminarDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="会议类别" align="center" prop="meetingName" />
      <!-- <el-table-column label="会议地点" align="center" prop="place" /> -->
      <el-table-column label="主持人" align="center" prop="emcee" />
      <el-table-column label="上报时间" align="center" prop="reportDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reportDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="记录人" align="center" prop="reporter" />
      <el-table-column label="签到表" align="center" prop="signUrl">
        <template #default="scope">
          <el-button @click.stop="previewFun(scope.row.signUrl)" v-if="scope.row.meetingUrl">查看</el-button>
          <span v-else>暂无数据</span>
        </template>
      </el-table-column>
      <el-table-column label="会议纪要" align="center" prop="meetingUrl">
        <template #default="scope">
          <el-button @click.stop="previewFun(scope.row.meetingUrl)" v-if="scope.row.meetingUrl">查看</el-button>
          <span v-else>暂无数据</span>
        </template>
      </el-table-column>
      <el-table-column label="现场照片" align="center" prop="imgUrl" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.imgUrl" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" :width="160">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['coordination:meeting:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['coordination:meeting:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改综合管理 会议对话框 -->
    <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <el-form ref="meetingRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="15"> <el-col :span="12" :xs="24">
            <el-form-item label="收费站" prop="deptId">
              <el-tree-select style="width:100%" class="inputDeep" v-model="form.deptId" :data="deptOptions" @node-click="handleNodeClick($event,'queryParams')"
                :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择" check-strictly clearable />
            </el-form-item>
          </el-col><el-col :span="12" :xs="24">
            <el-form-item label="会议时间" prop="seminarDate">
              <el-date-picker style="width:100%" clearable v-model="form.seminarDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择会议时间">
              </el-date-picker>
            </el-form-item>
          </el-col><el-col :span="12" :xs="24">
            <el-form-item label="会议类别" prop="meetingName">
              <el-input v-model="form.meetingName" placeholder="请输入会议类别" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12" :xs="24">
            <el-form-item label="会议地点" prop="place">
              <el-input v-model="form.place" placeholder="请输入会议地点" />
            </el-form-item>
          </el-col> -->
          <el-col :span="12" :xs="24">
            <el-form-item label="主持人" prop="emceeId">
              <el-select style="width:100%" v-model="form.emceeId" placeholder="请选择主持人">
                <el-option v-for="dict in usersList" :key="dict.userId" :label="dict.userName" :value="parseInt(dict.id)"></el-option>
              </el-select>
            </el-form-item>
          </el-col><el-col :span="12" :xs="24">
            <el-form-item label="记录人" prop="reporterId">
              <el-select style="width:100%" v-model="form.reporterId" placeholder="请选择记录人">
                <el-option v-for="dict in usersList" :key="dict.userId" :label="dict.userName" :value="dict.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col><el-col :span="12" :xs="24">
            <el-form-item label="现场照片" prop="imgUrl">
              <image-upload v-model="form.imgUrl" />
            </el-form-item>
          </el-col><el-col :span="12" :xs="24">
            <el-form-item label="签到表" prop="signUrl">
              <file-upload v-model="form.signUrl" />
            </el-form-item>
          </el-col><el-col :span="12" :xs="24">
            <el-form-item label="会议纪要" prop="meetingUrl">
              <file-upload v-model="form.meetingUrl" />
            </el-form-item>
          </el-col><el-col :span="24" :xs="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :rows="5" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <Viewer ref="fileViewerRef" :dialog-doc="dialogDoc" />
    <Statistics :echartsData="statisticsData" ref="statisticsRef" @changeType="handleStatistics" />
  </div>
</template>

<script setup name="Meeting">
import moment from "moment";
import { deptTreeSelect } from "@/api/system/user";
import { listMeeting, getMeeting, delMeeting, addMeeting, updateMeeting, getUsers,postMeetingCount } from "@/api/coordination/meeting";
import { getCKInfo } from '@/utils/auth'
import Viewer from "@/components/Custom/viewer.vue";
import { getListCharge } from "@/api/charge/charge";
import Statistics from "./components/Statistics.vue";
const { proxy } = getCurrentInstance();
const { upload_menu_type, coo_meeting_type } = proxy.useDict('upload_menu_type', 'coo_meeting_type');

const meetingList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeSeminarDate = ref([]);
const deptOptions = ref()
const dialogDoc = ref(false)
const fileViewerRef = ref()
const radioCon = ref('1')
const usersList = ref([])
const deptId = ref(Number(getCKInfo('deptId')))
const dateSection = ref([])
const statisticsData = ref({ series: [{ data: [] }, { data: [] }], xaxis: [] })
const statisticsRef = ref()

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: deptId.value,
    seminarDate: null,
    meetingName: null,
    cooMeetingType: radioCon.value,
    menuType: 13
  },
  rules: {
    deptId: [{ required: true, message: "收费站不能为空", trigger: "blur" }],
    seminarDate: [{ required: true, message: "会议时间不能为空", trigger: "blur" }],
    meetingName: [{ required: true, message: "会议名不能为空", trigger: "blur" }],
    imgUrl: [{ required: true, message: "现场照片不能为空", trigger: "blur" }],
    meetingUrl: [{ required: true, message: "会议纪要不能为空", trigger: "blur" }],
    signUrl: [{ required: true, message: "签到表不能为空", trigger: "blur" }],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询综合管理 会议列表 */
function getList() {
  loading.value = true;

  if( daterangeSeminarDate.value.length>0){
    queryParams.value.params = {};
    if (null != daterangeSeminarDate && '' != daterangeSeminarDate) {
    queryParams.value.params["beginSeminarDate"] = daterangeSeminarDate.value[0];
    queryParams.value.params["endSeminarDate"] = daterangeSeminarDate.value[1];
  }
  }

  listMeeting(queryParams.value).then(response => {
    meetingList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
function getUsersList() {
  getListCharge({deptId:deptId.value}).then(response => {
    usersList.value = response.rows;
  });

}

function handleStatistics(date) {
  // 本年  本季度  本月
  if (!date || !date.startDate) {
    date.startDate = moment().format('YYYY-MM') + '-01'
    date.endDate = moment().endOf('month').format('YYYY-MM-DD')
  }
  statisticsData.value.xaxis = []
  statisticsData.value.series[0].data = []
  postMeetingCount({
    "startTime": date.startDate,
    "endTime": date.endDate,
    "menuType": 13,
    meetingType:radioCon.value
  }).then(res => {
    if (res.code == 200 && res.data) {
      res.data.forEach(item => {
        statisticsData.value.xaxis.push(item.deptName)
        statisticsData.value.series[0].data.push(item.openCount)
      })
      statisticsRef.value.open();
    }
  })
}


/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
}

const bindRadio = (name, val) => {
  queryParams.value.cooMeetingType = val;
  radioCon.value = val;
  getList()
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deptId: deptId.value,
    cooMeetingType: radioCon.value,
    menuType: 13,
  };
  proxy.resetForm("meetingRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value={pageNum: 1,
    pageSize: 10,
    deptId: deptId.value};
  daterangeSeminarDate.value = [];
  dateSection.value=[]
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加" + coo_meeting_type.value.filter(item => item.value == radioCon.value)[0].label;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getMeeting(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改" + coo_meeting_type.value.filter(item => item.value == radioCon.value)[0].label;
  });
}
const bindChangeAllDate = (val) => {
  if (!val) { dateSection.value = []; queryParams.value.startDate = ''; queryParams.value.endDate = ''; return }
  dateSection.value = [moment(val[0]).format("YYYY-MM-DD"), moment(val[1]).format("YYYY-MM-DD")]
  queryParams.value.startDate = dateSection.value[0];
  queryParams.value.endDate = dateSection.value[1];
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["meetingRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateMeeting(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMeeting(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除综合管理 会议编号为"' + _ids + '"的数据项？').then(function () {
    return delMeeting(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('coordination/meeting/export', {
    ...queryParams.value
  }, `会务管理_${new Date().getTime()}.xlsx`)
}

// 预览
const previewFun = (file) => {
  const baseUrl = import.meta.env.VITE_APP_BASE_API;
  dialogDoc.value = true;
  let data = {};
  // 上传过的文件组成完成的网络路径
  if (file && file.indexOf(',') == -1) {
    data.src = `${baseUrl}${file}`;
  } else if (file && file.indexOf(',') != -1) {
    let src=file.split(',');
    let srcArr=[]
    src.forEach(item=>{srcArr.push(`${baseUrl}${item}`)})
    data.src = srcArr.join(',');
    file=srcArr[0]
  }

  const arr = file.split(".");
  const suffix = arr[arr.length - 1];
  if (suffix == "docx" || suffix == "doc") {
    fileViewerRef.value?.viewDocx(data, '研讨会');
  } else if (suffix == "xlsx" || suffix == "xls") {
    fileViewerRef.value?.viewXlsx(data);
  } else if (suffix == "jpg" || suffix == "jpeg" || suffix == "png") {
    fileViewerRef.value?.viewImg(data);
  } else if (suffix == "pdf") {
    fileViewerRef.value?.viewPdf(data);
  }
};
function handleNodeClick(data) {
  form.value.deptId = data.id;
}
getDeptTree();
getList();
getUsersList()
</script>

<style scoped>
.flex {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}
.flex-between {
  justify-content: space-between;
}

.flex .label {
  color: #333;
  font-size: 14px;
}
</style>